#include "gd32f30x.h"
#include "string.h"
#include "stdint.h"
#include "stdio.h"

#include "DevicesUID.h"

#include "uip.h"
#include "tapdev.h"
#include "uip_arp.h"
#include "timer.h"
#include "dhcps.h"
#include "dhcpc.h"

#include "taskNetwork.h"
#include "taskNetworkConnect.h"


struct uip_conn *g_ptypeUipConnectHandle[UIP_CONF_MAX_CONNECTIONS];

uint8_t g_ucNetworkMacAddr[6];

void vTaskNetworkConnect(void *pvParameters)
{
    uip_ipaddr_t typeIpAddr;

    /* DHCP客户端 */
    dhcpc_init(uip_ethaddr.addr, 6);
    dhcpc_request();


    /* UDP 广播端口 */
    uip_ipaddr(typeIpAddr, 255, 255, 255, 255);
    uip_udp_conn = uip_udp_new(&typeIpAddr, HTONS(UDP_PORT_BROADCAST));
    if(uip_udp_conn != NULL)
    {
        uip_udp_bind(uip_udp_conn, HTONS(UDP_PORT_BROADCAST));
    }

    /* UDP 消息端口 */
    uip_getdraddr(typeIpAddr);
    uip_udp_conn = uip_udp_new(&typeIpAddr, HTONS(UDP_PORT_MESSAGE));
    if(uip_udp_conn != NULL)
    {
        uip_udp_bind(uip_udp_conn, HTONS(UDP_PORT_MESSAGE));
    }


    /* TCP 消息端口 */
    uip_listen(HTONS(TCP_PORT_MESSAGE));


    while (1)
    {
        /* 新建 TCP 连接 */
        if(g_ptypeUipConnectHandle[0] == NULL)
        {
            uip_getdraddr(typeIpAddr);
            g_ptypeUipConnectHandle[0] = uip_connect(&typeIpAddr, HTONS(TCP_PORT_MESSAGE));
        }
    }
}
